﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace SSHTool.Util
{
    public static class ProcessUtil
    {
        public static void Start(string path, string args = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }
            try
            {
                string name = Path.GetFileNameWithoutExtension(path);
                var p = GetProcess(name);
                if (p == null)
                {
                    _ = Process.Start(path, args);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        public static void Kill(string name)
        {
            var p = GetProcess(name);
            if (p != null)
            {
                p.Kill();
            }
        }

        public static Process GetProcess(string name)
        {
            var ps = Process.GetProcessesByName(name);
            if (ps != null && ps.Length > 0)
            {
                return ps.FirstOrDefault();
            }
            return null;
        }

        public static Process GetCurrentProcess()
        {
            string name = GetCurrentProcessName();
            return GetProcess(name);
        }

        public static bool IsStarted(string name)
        {
            return GetProcess(name) != null;
        }

        public static string GetCurrentProcessName()
        {
            return Process.GetCurrentProcess().ProcessName;
        }

        public static bool CurrentProcessIsStarted()
        {
            string name = GetCurrentProcessName();
            
            return IsStarted(name);
        }
    }
}
